﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using planerka.DataAccess.Models;
using System.Text;
using planerka.DataAccess.DataService;
using planerka.Common;
using NLog;
using System.Configuration;
using planerka.Common.Enums;

namespace planerka.Web.Controllers
{
    public class AccountController : Controller
    {
        // Logger
        private static Logger logger = LogManager.GetCurrentClassLogger();

        // http://ctrlf5.net/?p=55
        // email verification

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // Вход на сайт
        public ActionResult Index()
        {
            return View();
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);

                    /*
                    // в сессии есть инвайты?
                    if (Session["inviteGuid"] != null)
                        return RedirectToAction("acceptInvite", (object) Session["inviteGuid"].ToString());
                    */

                    if (Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);
                    else
                        return RedirectToAction("Users", "tm");
                    
                }
                else
                {
                    ModelState.AddModelError("", "Имя пользователя или пароль неправильные.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Account");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // если есть пользователь с таким именем, и он не активирован - удалить его
                #region
                MembershipUser user = Membership.GetUser(model.Email);
                if (user != null)
                {
                    if (!user.IsApproved)
                        Membership.DeleteUser(model.Email, true);
                }
                #endregion

                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Email, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    // Сначала деактивировать пользователя
                    user = Membership.GetUser(model.Email);
                    user.IsApproved = false; // Activate the user
                    Membership.UpdateUser(user); // Update the user activation

                    MessagesService messagesService = new MessagesService();
                    List<SelectListItem> replaceItems = new List<SelectListItem>();
                    string userId = user.ProviderUserKey.ToString();
                    replaceItems.Add(new SelectListItem { Text = "{CONFIRM_URL}", Value = ConfigurationManager.AppSettings["siteURL"].TrimEnd('/') + "/tm/account/activateUser/" + userId });

                    messagesService.sendTemplatedEmail(replaceItems, model.Email, MessageTypes.PLEASE_ACTIVATE_EMAIL);
                    return View("RegisterSuccess"); 
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        

        // Активация аккаунта
        [HttpGet]
        public ActionResult activateUser(string id)
        {
            Guid userId = new Guid(id);
            MembershipUser user = Membership.GetUser(userId);
            if (user != null)
            {
                user.IsApproved = true; // Activate the user
                Membership.UpdateUser(user); // Update the user activation
                
                // создать пользователя с подтвержденным email
                new UserService().createUserWithApprovedEmail(user);
                FormsService.SignIn(user.Email, false /* createPersistentCookie */);

                // We success fully activate the user. Redirect somewhere
                return View("welcome");
            }
            else
                return RedirectToAction("Index", "Error");

            
        }

        // Принять приглашение пользователя,
        // при этом если 
        [HttpGet]
        [Authorize]
        public ActionResult acceptInvite(string id)
        {
           
            
                string resultMessage = "";
                string resultAcceptInviteFunction = acceptInviteFunction(id);
                if (resultAcceptInviteFunction != "")
                    resultMessage = "Вы успешно приняли приглашение от пользователя с email: " + resultAcceptInviteFunction;
                else
                    resultMessage = "Произошла ошибка. Нельзя обработать приглашение, проверьте правильность ссылки";

                
                return View("acceptInvite", (object)resultMessage);
            
            
        }

        [NonAction]
        public string acceptInviteFunction(string _Guid)
        {
            string inviteSenderEmail = "";
            Guid inviteGuid;

            if (Guid.TryParse(_Guid, out inviteGuid))
            { 
                UserService userService = new UserService();
                user currentUser = userService.getCurrentUser();
                
                userInvite _userInvite = userService.getInviteByGuid(inviteGuid);
                if (_userInvite != null)
                {
                    long fromUser_ID = _userInvite.user_ID;
                    user senderUser = userService.getUserByID(fromUser_ID);
                    if (senderUser != null)
                        inviteSenderEmail = senderUser.email;
                    
                    // это - разные пользователи?
                    if (fromUser_ID != currentUser.ID)
                    {
                        // активируем инвайт
                        userService.activateInvite(currentUser.ID, inviteGuid);

                        // и встречное предложение:
                        Guid? resGuid = userService.createInvite(currentUser.ID);
                        userService.activateInvite(fromUser_ID, (Guid)resGuid);
                    }
                }

            }
            
            return inviteSenderEmail;
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Текущий пароль неверный или новый пароль введен в неправильном формате.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
